package com.ruoyi.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.User;
import com.ruoyi.business.domain.bo.UserBo;
import com.ruoyi.business.domain.vo.UserVo;
import com.ruoyi.business.mapper.ClassInfoMapper;
import com.ruoyi.business.mapper.UserMapper;
import com.ruoyi.business.service.IUserService;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.InternalObjectPage;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.InnerObjVo;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysTableObjService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 最爱喝兽奶
 * @create 2022/7/13
 **/
@SuppressWarnings("ALL")
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysTableObjService sysTableObjService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Override
    public TableDataInfo getUserList(UserBo bo) {
        // 如果有教师id的话，就查询出这个教师所管理的班级
        if (null != bo.getClassIds() && bo.getClassIds().size() > 0) {

        }else {
            if (StringUtils.isNotBlank(bo.getTeacherId())) {
                // 查询出班级信息, 根据分配的老师的信息
                List<String> classIds = classInfoMapper.selectIdByTeacherId("%," + bo.getTeacherId() + ",%");
                bo.setClassIds(classIds);
            }
        }
        Page<UserVo> page = userMapper.selectUserVoByPage(PageUtils.buildPage(bo), bo);
        return PageUtils.buildTableDataInfo(page);
    }

    @Override
    public UserVo getVoById(String userId) {
        if (StringUtils.isNotBlank(userId)) {
            User user = getById(userId);
            UserVo vo = new UserVo();
            BeanUtils.copyProperties(user, vo);
            // 设置用户分组
            // 查询用户所扮演的角色
            SysRole role = baseMapper.queryRoleByUserId(userId);
            vo.setGroup(String.valueOf(role.getRoleId()));
            vo.setGroupName(role.getRoleName());
            vo.setUserId(userId);
            vo.setPassword(null);
            return vo;
        }
        return null;
    }

    @Override
    public List<InnerObjVo> queryGroupRef() {
        List<InnerObjVo> vos = baseMapper.queryGroupRef();
        return vos;
    }

    @Override
    public InternalObjectPage selectRefTableByName(String refColumn, Integer pageSize, Integer currentPage, String filterContent, String filterId) {
        InternalObjectPage pageDomain = new InternalObjectPage();
        //主键Map
        Map<String, String[]> pkMap = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        //标题头
        Map<String, Map<String, String>> titleMap = new LinkedHashMap();
        String sql = null;
        Page pageList = new Page();
        Page page = new Page();
        //是否开启分页，不开启默认查询前10000条记录（前端已限制默认分页数量，此处为保障内部对象的正常使用）
        if (currentPage == null || pageSize == null) {
            page = new Page(1, 10000);
        } else {
            page = new Page(currentPage, pageSize);
        }
        String[] refColumns = {"teacher"};
        if (StringUtils.equalsAnyIgnoreCase(refColumn, refColumns)) {

            Map<String, String> teacherMap = new LinkedHashMap();
            teacherMap.put("showColumn", "教师");
            titleMap.put("teacher", teacherMap);
            pkMap.put("teacher", new String[]{"su.user_id", "su.user_name"});
            map.put("teacher", "SELECT su.user_id as \"refColumn\", su.nick_name as \"showColumn\"   FROM sys_user su left join sys_user_role sur on su.user_id = sur.user_id where sur.role_id = 2 ");

            sql = map.get(refColumn);
            //筛选
            if (StringUtils.isNotEmpty(filterContent)) {
                if (StringUtils.isNotEmpty(pkMap.get(refColumn)[1])) {
                    sql = sql + " and " + pkMap.get(refColumn)[1] + " like " + "'%" + filterContent + "%'";
                }
            }
            //回显与判断
            if (StringUtils.isNotEmpty(filterId)) {
                List<String> list = Arrays.asList(filterId.split(","));
                String ids = list.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
                if (StringUtils.isNotEmpty(pkMap.get(refColumn))) {
                    sql = sql + " and " + pkMap.get(refColumn)[0] + " in " + "(" + ids + ")";
                }
            }
        }
        try {
            pageList = sysTableObjService.executeSelectSqlSelectRefTableByName(page, sql);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException().setMessage("内部对象字段配置信息错误");
        }
        List<Map<String, String>> records = (List<Map<String, String>>) pageList.getRecords().stream().map(item -> {
            if (item instanceof Map) {
                Map m = (Map) item;
                if (m.containsKey("refColumn")) {
                    Object value = m.get("refColumn");
                    if (value instanceof BigInteger) {
                        m.put("refColumn", String.valueOf(value));
                    } else if (value instanceof Long) {
                        m.put("refColumn", String.valueOf(value));
                    }
                }
            }
            return item;
        }).collect(Collectors.toList());
        pageDomain.setTotal(page.getTotal());
        pageDomain.setTitle(titleMap.get(refColumn));
        pageDomain.setDataList(records);
        return pageDomain;
    }

    @Override
    public void insertUser(UserBo bo) {
        User user = new User();
        BeanUtils.copyProperties(bo, user);
        // 插入用户信息
        // 将用户密码加密
        String s = SecurityUtils.encryptPassword(bo.getNewPassword());
        user.setPassword(s);
        // 插入分组
        baseMapper.insert(user);
        baseMapper.insertUserRole(user.getUserId(), bo.getGroup());
    }

    @Override
    public void updateUser(UserBo bo) {
        User user = new User();
        BeanUtils.copyProperties(bo, user);
        // 修改用户信息
        // 判断是否需要修改密码
        if (StringUtils.isNotBlank(bo.getNewPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(bo.getNewPassword()));
        }
        // 判断是否需要修改分组
        UserVo vo = getVoById(bo.getUserId());
        if (!vo.getGroup().equals(bo.getGroup()) && StringUtils.isNotBlank(bo.getGroup())) {
            baseMapper.updateUserRole(bo.getUserId(), bo.getGroup());
        }
        baseMapper.updateById(user);
    }

    @Override
    public void deleteUser(String id) {
        // 删除用户表里的数据，删除用户角色关联数据
//        userMapper.deleteById(id);
        // 删除关联关系
//        sysUserRoleMapper.deleteUserRoleByUserId(Long.parseLong(id));
        // 逻辑删除
        userMapper.updateDelFlagById(id);
    }

    @Override
    public void insertUserList(List<UserBo> boList) {
        for (UserBo userBo : boList) {
            insertUser(userBo);
        }
    }

    @Override
    @Transactional
    public void insertUserListCover(List<UserBo> boList) {
        for (UserBo userBo : boList) {
            // 先查询当前是否存在学号
            String userName = userBo.getUserName();
            User user = baseMapper.selectOne(new QueryWrapper<User>().eq("user_name", userName));
            if (null == user) {
                insertUser(userBo);
            }else {
                BeanUtils.copyBeanProp(user, userBo, false);
                baseMapper.updateById(user);
                // 查询用户角色是否发生了变化
                String group = userBo.getGroup();
                SysUserRole userRole = baseMapper.selectUserRole(user.getUserId(), group);
                if (null == userRole) {
                    baseMapper.updateUserRole(user.getUserId(), group);
                }
            }
        }
    }

    private Wrapper<User> buildQueryWrapper(UserBo bo) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(StringUtils.isNotEmpty(bo.getUserName()), User::getUserName, bo.getUserName());


        return wrapper;
    }
}
